package me.zingon.service;

import me.zingon.common.Constant;
import me.zingon.dao.LogDao;
import me.zingon.model.Log;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;


@Service
public class LogService {
    @Autowired
    CloseableHttpClient httpClient;

    @Autowired
    RequestConfig requestConfig;

    @Autowired
    LogDao logDao;

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void saveIpinfo(final Log log) throws IOException {
        Log l = logDao.getLog(log.getSession());
        if (l != null) {
            log.setId(l.getId());
            logDao.updateLog(log);
            return;
        }
        log.setLocation(getIpLocation(log.getIp()).split("=")[3]);
        logDao.saveLog(log);
    }

    public String getIpLocation(String ip) throws IOException {
        HttpGet get = new HttpGet(Constant.GetIpLocationUrl + "?ip=" + ip);
        CloseableHttpResponse res = httpClient.execute(get);
        return EntityUtils.toString(res.getEntity());
    }
}
